package com.meeting.meetingroom_api.controller;

import com.meeting.meetingroom_api.dto.LoginRequestDto;
import com.meeting.meetingroom_api.dto.LoginResponseDto; 
import com.meeting.meetingroom_api.dto.UserDto;
import com.meeting.meetingroom_api.security.JwtUtil; 
import com.meeting.meetingroom_api.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager; 
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 
import org.springframework.security.core.Authentication; 
import org.springframework.security.core.context.SecurityContextHolder; 
import org.springframework.security.core.userdetails.UserDetails; 
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    public AuthController(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService; 

    @PostMapping("/login")
    public ResponseEntity<?> loginUser(@RequestBody LoginRequestDto loginRequestDto) {
        try {
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginRequestDto.getUsername(), loginRequestDto.getPassword()));

            SecurityContextHolder.getContext().setAuthentication(authentication);
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String jwt = jwtUtil.generateToken(userDetails);

            UserDto userDto = userService.getUserByUsername(userDetails.getUsername()); 
            if (userDto == null) { 
                 return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("无法检索用户信息。");
            }

            return ResponseEntity.ok(new LoginResponseDto(jwt, userDto));

        } catch (org.springframework.security.core.AuthenticationException e) {
            // AuthenticationException 是更具体的登录失败异常
            System.out.println("登录失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("登录失败：用户名或密码错误。");
        } catch (Exception e) {
            System.out.println("登录过程中发生未知错误：" + e.getMessage());
            e.printStackTrace(); // 打印堆栈跟踪以进行调试
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("登录过程中发生内部错误: " + e.getMessage());
        }
    }
}